import React, {Component} from 'react'
import './index.css'
import Header from "@/NewTodo/components/Header";
import Main from "@/NewTodo/components/Main";
import Footer from "@/NewTodo/components/Footer";
import {produce} from "immer";
import {ACTIVE, ALL, COMPLETE} from "./constants/index";
import {random} from "lodash";


class App extends Component {

  componentDidMount() {
    this.setState({
      list: JSON.parse(localStorage.getItem('todos'))
    })
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    localStorage.setItem('todos', JSON.stringify(this.state.list))
  }

  state = {
    checkAll: false,
    status: ALL,
    list: []
  }

  setStatus = (status) => () => {
    console.log(status)
    this.setState({
      status
    })
  }

  clear = () => {
    this.setState({
      list: this.state.list.filter(item => !item.isDone)
    })
  }

  onChange = (id, status) => {
    this.setState(produce(state => {
      const currentEvent = state.list.find(item => item.id === id)
      currentEvent.isDone = status
    }))
  }

  addTodo = (title) => {
    this.setState(produce(state => {
      state.list.push({
        id: random(100, 1000),
        title,
        isDone: false
      })
    }))
  }


  delTodo = id => () => {
    this.setState({
      list: this.state.list.filter(item => item.id !== id)
    })
  }

  changeAll = (checked) => {
    this.setState(produce(state => {
      state.list.forEach(item => {
        item.isDone = checked
      })
      state.checkAll = checked
    }))
  }

  editTodo = (title, id) => {
    this.setState(produce(state => {
      state.list.forEach(item => {
        if (item.id === id) {
          item.title = title
        }
      })
    }))
  }

  render() {
    const {status} = this.state
    const showList = this.state.list.filter(item => {
      if (status === ACTIVE) {
        return !item.isDone
      }
      if (status === COMPLETE) {
        return item.isDone
      }
      return true
    })
    return (
      <section className="todoapp">
        <Header addTodo={this.addTodo}/>
        <Main
          editTodo={this.editTodo}
          addTodo={this.addTodo}
          changeAll={this.changeAll}
          checkAll={this.state.checkAll}
          delTodo={this.delTodo}
          status={this.state.status}
          list={showList}
          onChange={this.onChange}
        />
        <Footer len={showList.length} clear={this.clear} status={this.state.status} setStatus={this.setStatus}/>
      </section>
    )
  }
}


export default App
